package cn.android666.nopreviewcamera

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import androidx.core.graphics.createBitmap
import androidx.core.graphics.toColorInt

/**
 * 水印生成器
 */
object WatermarkProducer {

    private val strokePaint = createTextPaint(Color.BLACK, Paint.Style.STROKE)
    private val fillPaint = createTextPaint(Color.WHITE, Paint.Style.FILL)
    private val canvas = Canvas()

    fun createTextBitmap(text: String, colorConfig: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap {
        val fontMetrics = fillPaint.fontMetricsInt
        var textWidth = fillPaint.measureText(text).toInt()
        var textHeight = fontMetrics.descent - fontMetrics.ascent

        // 预防宽高出现奇数
        textWidth += textWidth % 2
        textHeight += textHeight % 2

        val bitmap = createBitmap(textWidth, textHeight, colorConfig)
        canvas.setBitmap(bitmap)
        if (colorConfig == Bitmap.Config.RGB_565) {
            canvas.drawColor("#0000FF".toColorInt())
        }

        val y = (fontMetrics.leading - fontMetrics.ascent).toFloat()
        canvas.drawText(text, 0f, y, strokePaint)
        canvas.drawText(text, 0f, y, fillPaint)
        return bitmap
    }

    private fun createTextPaint(paintColor: Int, paintStyle: Paint.Style): Paint {
        return Paint().apply {
            color = paintColor
            style = paintStyle
            isAntiAlias = false
            textSize = 16f
            strokeWidth = 2f
        }
    }
}